import React, { useState } from 'react';
import _ from 'lodash';
import { Button, Modal, Space, Table, TableProps, message } from 'antd';
import {
  FormPanel,
  MinioUploadListType,
  FormPanelType,
  type FormPanelObject,
  FormPanelStatus,
  InputType,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  Utils,
} from 'lfun-bg-comp';
import { useLocation, useParams } from 'react-router-dom';
import styles from './index.less';
import { KG_ORDER_STATUS, SCHOOL_TYPE } from '@/constant/schoolOptions';
import { getCity, getProvince } from '@/service';
import { createCampus, openCampus, searchCampus, updateCampus, closeCampus } from '@/service/unit/campus';
import utils, { buildPageItemTxtByEduType, get_stoge_pz, set_stoge_pz } from '@/utils';
import { PAGINATIONCONFIG } from '@/constant/page';
import useCountry from '@/hooks/useCountry';
import { isPermissionOperate } from '@/component/permission-button';

// eslint-disable-next-line react/require-default-props
const Groups: React.FC<{ value?: any; isEdit?: boolean }> = ({ value, isEdit = true }) => {
  const [showModel, setShowModel] = React.useState(false);
  const location = useLocation();
  const [formPanelObject, setFormPanelObject] = React.useState<FormPanelObject>();
  const [upformPanelObject, setupFormPanelObject] = React.useState<any>();

  const [v, setV] = React.useState(value);
  const [showViewModel, setShowViewModel] = React.useState(false);
  const [curView, setCurView] = React.useState<any>({});
  const [editViewModel, setEditViewModel] = React.useState(false);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz(10, 'add-area'));
  const [pageIndex, setPageIndex] = React.useState(1);
  const [saveLoading, setSaveLoading] = React.useState(false);
  const [showCloseModel, setShowCloseModel] = React.useState(false);
  const isSchool = Utils.getProps('isSchool');
  const country = useCountry();
  const [province, setProvince] = useState([]);
  const [location_district, set_location_district] = useState([]);
  const { id } = useParams();

  const closeList: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '关闭原因',
          name: 'action_reason',
          key: 'action_reason',
          required: true,
          textRange: [0, 20],
          span: 24,
        },
        {
          span: 24,
          label: '上传相关证件照',
          name: 'related_license_upload',
          key: 'related_license_upload',
          inputType: InputType.minioUpload,
          props: {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
          },
          inputProps: {
            placeholder: '请输入相关证件上传',
            listType: MinioUploadListType.picture,
            text: '浏览',
            maxCount: 1,
          },
        },
      ],
    },
  ];
  const newFileds: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '校区名称',
          name: 'campus_name',
          key: 'campus_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '校区代码',
          name: 'campus_no',
          key: 'campus_no',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '联系电话',
          name: 'contact_number',
          key: 'contact_number',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '传真',
          name: 'fax_number',
          key: 'fax_number',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '校区负责人姓名',
          name: 'campus_leader_name',
          key: 'campus_leader_name',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '校区负责人职位',
          name: 'campus_leader_position',
          key: 'campus_leader_position',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '所在经度',
          name: 'long',
          key: 'long',
          required: true,
          inputProps: {
            placeholder: '请输入所在经度 如经度123.4',
          },
          textRange: [0, 10],
        },
        {
          label: '所在纬度',
          name: 'lat',
          key: 'lat',
          required: true,
          inputProps: {
            placeholder: '请输入所在纬度 如纬度41.7',
          },
          textRange: [0, 10],
        },
        {
          label: '校区成立日期',
          name: 'create_campus_date',
          key: 'create_campus_date',
          required: true,
          inputType: InputType.date,
          formatSubmitValue: (value: any) => {
            if (value && value.isValid && value.isValid()) {
              return value.format('YYYY-MM-DD');
            }
            return value;
          },
        },
        {
          label: '电子邮箱',
          name: 'email',
          key: 'email',
          ruleType: 'email',
          required: true,
        },
        {
          label: '校区所在地(省市)',
          name: 'location_city',
          key: 'location_city',
          required: true,
          inputType: InputType.select,
          relationFields: ['location_district'],
          renderOption: async () => {
            const r = await getProvince();
            if (r.success) {
              return r.data?.items?.map(item => {
                return {
                  label: item.description,
                  value: item.enum_value,
                };
              });
            }
            return [];
          },
        },
        {
          label: '校区所在地(区县)',
          name: 'location_district',
          key: 'location_district',
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            if (form.getFieldsValue().location_city) {
              const r = await getCity(form.getFieldsValue().location_city);
              if (r?.success) {
                return r?.data?.items?.map(item => ({
                  label: item.description,
                  value: item.enum_value,
                }));
              }
            }
            return [];
          },
        },
        {
          label: '邮编',
          name: 'postal_code',
          key: 'postal_code',
          ruleType: 'cnPostalCode',
          required: true,
        },
        {
          label: '学校详细地址',
          name: 'detailed_address',
          key: 'detailed_address',
          required: true,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
          },
          span: 24,
          textRange: [0, 100],
        },
        {
          span: 24,
          label: '上传相关证件照',
          name: 'related_license_upload',
          key: 'related_license_upload',
          inputType: InputType.minioUpload,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
          },
          inputProps: {
            placeholder: '请输入相关证件上传',
            listType: MinioUploadListType.picture,
            text: '浏览',
            maxCount: 1,
          },
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '校区代码',
      dataIndex: 'campus_no',
      key: 'campus_no',
      align: 'center',
    },
    {
      title: '校区名称',
      dataIndex: 'campus_name',
      key: 'campus_name',
      align: 'center',
    },
    {
      title: '校区所在地(省市)',
      dataIndex: 'location_city',
      key: 'location_city',
      align: 'center',
      render: (text: any) => {
        return _.find(province, { value: String(text) })?.label;
      },
    },
    {
      title: '校区所在地(区县)',
      dataIndex: 'location_district',
      key: 'location_district',
      align: 'center',
      render: (text: any) => {
        return _.find(location_district, { value: String(text) })?.label;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text: any) => {
        return _.find(KG_ORDER_STATUS, { value: text })?.label;
      },
    },
    {
      title: '校区成立日期',
      dataIndex: 'create_campus_date',
      key: 'create_campus_date',
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      dataIndex: 'operation',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text: any, record: any) => {
        return (
          <Space>
            {isSchool && isEdit ? (
              <Button
                type="link"
                onClick={() => {
                  setCurView(record);
                  setEditViewModel(true);
                }}
              >
                编辑
              </Button>
            ) : (
              ''
            )}
            <Button
              type="link"
              size="small"
              onClick={() => {
                setShowViewModel(true);
                setCurView(record);
              }}
            >
              查看
            </Button>
            {isSchool && (
              <Button
                type="link"
                size="small"
                onClick={() => {
                  setCurView(record);
                  setShowCloseModel(true);
                }}
              >
                关闭
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  const buildBtns = () => {
    return [
      <Button
        key="save"
        type="primary"
        loading={saveLoading}
        onClick={async () => {
          setSaveLoading(true);
          const r = await save(formPanelObject, true);
          if (r) {
            setShowModel(false);
          }
          setSaveLoading(false);
        }}
      >
        保存
      </Button>,
      <>
        {v?.status !== 'nomal' ? (
          <Button
            type="link"
            onClick={() => {
              formPanelObject.resetFields();
              setShowModel(false);
            }}
          >
            取消
          </Button>
        ) : (
          ''
        )}
      </>,
    ];
  };

  const init = async (pSize, pIndex) => {
    const res = await searchCampus({ school_id: id || location?.state?.id }, 1, 10);
    if (res.success) {
      setV(res.data.items);
      setTotal(res.data.total);
      setPageSize(pSize);
      setPageIndex(pIndex);
    }
  };
  const _getProvince = async () => {
    const res = await getProvince();
    if (res.success) {
      const options = res.data?.items?.map(item => {
        return {
          label: item.description,
          value: item.enum_value,
        };
      });
      setProvince(options);
    }
  };
  const _getCity = async () => {
    const r = await getCity();
    if (r?.success) {
      const options = r?.data?.items?.map(item => ({
        label: item.description,
        value: item.enum_value,
      }));
      set_location_district(options);
    }
  };
  React.useEffect(() => {
    searchCampus({ school_id: id || location?.state?.id }, 1, 1000).then(res => {
      if (res.success) {
        setV(res.data.items);
      }
    });
    _getProvince();
    _getCity();
  }, []);
  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize, 'add-area');
    init(pageSize, pageIndex);
  };

  const save = async (panelObject: any, isShowToast: boolean) => {
    if (curView && curView.id) {
      const values: any = utils.unflattenObject(upformPanelObject.getFieldsValue());
      const campus: any = { ...values, school_id: location.state.id };
      //campus.create_campus_date = values.create_campus_date.format('YYYY-MM-DD');
      const res = await updateCampus(curView.id, campus);
      if (res.success) {
        if (isShowToast) message.success('修改成功');
        return res.data;
      }
      panelObject.reVaildation(res);
    } else {
      const values: any = utils.unflattenObject(formPanelObject.getFieldsValue());
      const campus: any = { ...values, school_id: location.state.id };
      // if (values.create_campus_date) {
      //   campus.open_campus_date = values.open_campus_date.format('YYYY-MM-DD');
      // }
      //campus.create_campus_date = values.create_campus_date.format('YYYY-MM-DD');
      const res = await createCampus(campus);
      if (res.success) {
        setCurView(res);
        if (isShowToast) message.success('新增成功');
        setShowModel(false);
        init(pageSize, 1);
        return res.data;
      }
      panelObject.reVaildation(res);
    }
    return null;
  };
  return (
    <>
      {isSchool && (
        <Button type="default" className={`${styles.add_leader_btn} add_leader_btn`} onClick={() => setShowModel(true)}>
          新增校区
        </Button>
      )}
      <Table
        dataSource={v}
        columns={columns}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal width="80%" title="新增校区" footer={[]} open={showModel} onCancel={() => setShowModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          isShowDefBtn={v?.status === 'nomal'}
          restBtnText="返回"
          submitBtnText="正式开办"
          onLoad={(formPanelObject: FormPanelObject) => {
            setFormPanelObject(formPanelObject);
          }}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const upres = await save(formPanelObject, false);
            if (upres) {
              const opres: any = await openCampus(upres.id);
              if (opres.success) {
                message.success('正式开办成功');
                setShowModel(false);
                formPanelObject.resetFields();
              } else {
                formPanelObject.reVaildation(opres);
              }
            } else {
              message.error('新增校区失败');
            }
          }}
          buttons={buildBtns()}
          onReset={form => {
            form.resetFields();
            setShowModel(false);
          }}
        />
      </Modal>
      <Modal width="80%" title="查看校区" footer={[]} open={showViewModel} onCancel={() => setShowViewModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          buttonsDisplay={FormPanelBtnDisplay.none}
          formStatus={FormPanelStatus.nonEdit}
          values={curView}
          onReset={form => {
            form.resetFields();
            setShowModel(false);
          }}
        />
      </Modal>
      <Modal width="80%" title="编辑校区" footer={[]} open={editViewModel} onCancel={() => setEditViewModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="保存"
          values={curView}
          onLoad={(formPanelObject: FormPanelObject) => {
            //setCurupForm(form);
            setupFormPanelObject(formPanelObject);
          }}
          onFinish={async (formPanelObject: FormPanelObject) => {
            setSaveLoading(true);
            const r = await save(upformPanelObject, true);
            if (r) {
              setEditViewModel(false);
            }
            setSaveLoading(false);
            init(pageSize, 1);
            return false;
          }}
          onReset={(form: FormPanelObject) => {
            form.resetFields();
            setEditViewModel(false);
          }}
        />
      </Modal>
      <Modal width="800px" title="关闭" footer={[]} open={showCloseModel} onCancel={() => setShowCloseModel(false)}>
        <FormPanel
          template={closeList}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          onLoad={(formPanelObject: FormPanelObject) => {
            setFormPanelObject(formPanelObject);
          }}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const opres: any = await closeCampus(curView.id, formPanelObject.getFieldsValue());
            if (opres.success) {
              message.success('关闭成功');
              setShowCloseModel(false);
              formPanelObject.resetFields();
            } else {
              message.error('关闭失败');
              formPanelObject.reVaildation(opres);
            }
          }}
          onReset={form => {
            form.resetFields();
            setShowCloseModel(false);
          }}
        />
      </Modal>
    </>
  );
};

export default Groups;
